﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.Text;
using System.IO;
using System.Data;
using System.Text.RegularExpressions;
using System.Collections;
/// <summary>
///生成静态页面方法
/// </summary>
public static class SetToHtml
{
    /// <summary>
    /// 生成静态页面
    /// </summary>
    /// <param name="moban">模板地址</param>
    /// <param name="dizhi">文件保存地址</param>
    /// <param name="Canshu">参数</param>
    /// <returns></returns>
    public static bool ToHtml(string moban, string dizhi, Hashtable Canshu)
    {
        //生成页面
        try
        {
            StringBuilder strhtml = new StringBuilder();
            //创建StreamReader对象
            using (StreamReader sr = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("~/") + moban, Encoding.GetEncoding("gb2312")))
            {
                String oneline;
                //读取指定的HTML文件模板
                while ((oneline = sr.ReadLine()) != null)
                {
                    strhtml.Append(oneline);
                }
                sr.Close();
            }

            //遍历Hashtable中的键跟值，同时进行关键字替换
            System.Collections.IDictionaryEnumerator enumerator = Canshu.GetEnumerator();
            while (enumerator.MoveNext())
            {
                strhtml = strhtml.Replace(enumerator.Key.ToString(), enumerator.Value.ToString());
            }
            string FilePath = System.Web.HttpContext.Current.Server.MapPath("~/") + dizhi;
            //删除原有文件
            FileInfo file = new FileInfo(FilePath);
            if (file.Exists)
            {
                file.Delete();
            }
            //创建文件信息对象--------------------------------------------
            FileInfo finfo = new FileInfo(FilePath);
            //以打开或者写入的形式创建文件流
            using (FileStream fs = finfo.OpenWrite())
            {
                //根据上面创建的文件流创建写数据流
                StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Default);
                //把新的内容写到创建的HTML页面中
                sw.WriteLine(strhtml);
                sw.Flush();
                sw.Close();
            }
        }
        catch (Exception err)
        {
            //输出异常信息
            throw new Exception(err.Message, err);
        }
        return true;

    }
}